﻿using System;
using System.Collections.Generic;
using System.Linq;
using CML.Intercamber.Business.Model;

namespace CML.Intercamber.Business.Dao
{
    public class TranslationHistoryDao
    {
        public static List<TranslationHistoryDetail> ListTranslationsHistory(long idUser)
        {
            List<TranslationHistoryDetail> res;
            using (var context = new IntercamberEntities())
            {
                res = (from x in context.TranslationHistory
                       where x.IdUser == idUser
                       orderby new { x.Starred, x.DateSearch} descending 
                       select new TranslationHistoryDetail{
                           IdTranslationHistory = x.IdTranslationHistory, 
                           IdLanguage = x.IdLanguage, 
                           IdUser = x.IdUser, 
                           Starred = x.Starred, 
                           Word = x.Word, 
                           Date = x.DateSearch
                    }).ToList();
            }
            return res;
        }

        public static void InsertTranslationHistory(TranslationHistory item)
        {
            using (var context = new IntercamberEntities())
            {
                item.DateSearch = DateTime.Now;
                context.TranslationHistory.Add(item);
                context.SaveChanges();
            }
        }

        public static void ToggleTranslationHistoryStar(long idTranslationHistory, bool starred)
        {
            using (var context = new IntercamberEntities())
            {
                var item = context.TranslationHistory.FirstOrDefault(x => x.IdTranslationHistory == idTranslationHistory);
                if (item == null)
                    return;
                item.Starred = starred;
                context.SaveChanges();
            }
        }

        public static void DeleteTranslationHistory(long idTranslationHistory)
        {
            using (var context = new IntercamberEntities())
            {
                var item = context.TranslationHistory.FirstOrDefault(x => x.IdTranslationHistory == idTranslationHistory);
                if (item == null)
                    return;
                context.TranslationHistory.Remove(item);
                context.SaveChanges();
            }
        }

    }
}
